﻿using Quartz;
using System;
using ezCloud.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
using ezCloud.Data.Enum;
using System.IO;

namespace ezCloud.SendEmailMarketingBySchedule.Job
{
    public class EmailJob : IJob
    {
        #region Properties

        private ezCloudDataContext DataContext = new ezCloudDataContext();
        private DateTime currentDate = DateTime.UtcNow;

        #endregion
        public void Execute(IJobExecutionContext context)
        {
            List<HotelEmailLog> listEmailNeedSend = new List<HotelEmailLog>();

            listEmailNeedSend.AddRange(GetQueueEmail());

            if (listEmailNeedSend != null && listEmailNeedSend.Count > 0)
            {
                listEmailNeedSend.ForEach(x =>
                {
                    var oldLog = DataContext.HotelEmailLog.Where(y => y.HotelEmailLogId == x.HotelEmailLogId).Single();
                    bool isSendMailSuccess = SendMailByLogId(x);
                    oldLog.Status = isSendMailSuccess ? (int)SendMailStatus.Success : (int)SendMailStatus.Fail;

                    //DataContext.SubmitChanges();
                });
            }

        }
        #region Private Methods
        private bool SendMailByLogId(HotelEmailLog log)
        {
            bool isSuccess = false;
            HotelEmailConfig configEmail;
            if (log.HotelEmailTask.HotelEmailConfig != null)
            {
                configEmail = log.HotelEmailTask.HotelEmailConfig;
            }
            else
            {
                configEmail = DataContext.HotelEmailConfig.Where(x => x.HotelId == log.HotelId).FirstOrDefault();
            }

            try
            {
                using (var message = new MailMessage(configEmail.UserName, log.ReservationRooms.Travellers.Email))
                {
                    message.Subject = log.HotelEmailTask.Subject;
                    message.Body = File.ReadAllText(log.Link);
                    if (!string.IsNullOrEmpty(log.HotelEmailTask.EmailCC))
                    {
                        log.HotelEmailTask.EmailCC.Split(';').ToList().ForEach(x =>
                        {
                            message.CC.Add(x);
                        });
                    }
                    using (SmtpClient client = new SmtpClient
                    {
                        EnableSsl = true,
                        Host = configEmail.ServerName,
                        Port = configEmail.Port,
                        Credentials = new NetworkCredential(configEmail.UserName, configEmail.PassEmail)
                    })
                    {
                        client.Send(message);
                        isSuccess = true;
                    }
                }
            }
            catch (Exception)
            {
                isSuccess = false;
            }
            return isSuccess;
        }

        private IEnumerable<HotelEmailLog> GetQueueEmail()
        {
            List<HotelEmailLog> result = new List<HotelEmailLog>();
            result = DataContext.HotelEmailLog.Where(x => x.Status == (int)SendMailStatus.Processing && !string.IsNullOrEmpty(x.Link)).OrderBy(x => x.CreatedAt).Skip(10).ToList();
            return result;
        }
        #endregion

    }
}